package com.mall.order.mq;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;


@Component
public class OrderProducer {
    @Value("${mq.producergroup}")
    String producergroup;

    @Value("${mq.addr}")
    String addr;

    @Value("${mq.topic}")
    String topic;


    DefaultMQProducer mqProducer;

    @PostConstruct
    public void init() {
        mqProducer = new DefaultMQProducer(producergroup);
        mqProducer.setNamesrvAddr(addr);
        try {
            mqProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public void sendOrderOverTimeMsg(String orderId, Integer userId) {
        Map map = new HashMap<String, Object>();
        map.put("orderId", orderId);
        map.put("userId", userId);

        String jsonString = JSON.toJSONString(map);

        Message message = new Message(topic, jsonString.getBytes(Charset.forName("utf-8")));

        ////messageDelayLevel=  1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        message.setDelayTimeLevel(2);

        try {
            mqProducer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}

